package com.iflytek.cosmo.ocr.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.iflytek.cosmo.ocr.common.config.VersionSettingProperties;
import com.iflytek.cosmo.ocr.common.constant.AbstractExceptionCodeConstant;
import com.iflytek.cosmo.ocr.common.constant.AbstractExceptionDescribeConstant;
import com.iflytek.cosmo.ocr.common.exception.ParseDownLoadUrlExceptionAbstract;
import com.iflytek.cosmo.ocr.service.SettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SettingServiceImpl implements SettingService {

    /**
     * 日志记录器
     */
    private Logger logger = LoggerFactory.getLogger(SettingServiceImpl.class);

    /**
     * 版本配置类
     */
    @Autowired
    private VersionSettingProperties versionSettingProperties;

    @Value("${server.context-path}")
    private String contextPath;

    @Value("${server.port}")
    private Integer port;

    /**
     * 传入数据库配置的相对路径,拼接成绝对路径返回
     *
     * @throws ParseDownLoadUrlExceptionAbstract
     */
    @Override
    public String getPackageAbsoluteUrl(String relativePath) throws ParseDownLoadUrlExceptionAbstract {
        // 配置文件中读取绑定的ip
        String bindIp = versionSettingProperties.getBindIp();
        // 安装包的存放路径可配置部分
        String urlMapping = versionSettingProperties.getPackageMappingBaseUrl();
        // ip类型 ：http 或者https
        String schema = versionSettingProperties.getPackageUrlSchema();

        if (StringUtil.isEmpty(bindIp) || StringUtil.isEmpty(urlMapping) || StringUtil.isEmpty(schema)
                || StringUtil.isEmpty(contextPath) || port == null) {
            //绝对路径所需参数不足抛出异常
            logger.error("relativePath:{}, 异常ParseDownLoadUrlException:{}", relativePath,
                    AbstractExceptionDescribeConstant.DOWNLOAD_URL_EXCEPTION);
            throw new ParseDownLoadUrlExceptionAbstract("异常代码:" + AbstractExceptionCodeConstant.TARGET_NOT_EXIST_EXCEPTION_CODE);
        }

        // 如果配置了ip
        StringBuilder sb = new StringBuilder();
        sb.append(schema);// http 或者 https
        sb.append("://");
        sb.append(bindIp);// ip
        sb.append(":");
        sb.append(port);// 端口
        sb.append(contextPath);// 上下文
        // 不是以"/"开始
        if (!urlMapping.startsWith("/")) {
            urlMapping = "/" + urlMapping;
        }
        // 不是以"/"结束
        if (!urlMapping.endsWith("/")) {
            urlMapping = urlMapping + "/";
        }
        sb.append(urlMapping);
        // 格式化相对路径
        if (relativePath.startsWith("/")) {
            relativePath = (String)relativePath.subSequence(1, relativePath.length());
        }
        sb.append(relativePath);
        // 绝对路径
        String packageAbsoluteUrl = sb.toString();

        return packageAbsoluteUrl;
    }
}
